/**
 *   This file is part of WiFiStorer.

    WiFiStorer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WiFiStorer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WiFiStorer.  If not, see <http://www.gnu.org/licenses/>.
    
    @author Ontic Soluciones
    @license GNU GPLv3
    @copyright 2010 Ontic Soluciones
    @link http://www.ontic.es
    @contact android@ontic.es
 */


package com.Storer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Muestra la lista de las tablas que hay en la base de datos y las exporta a formato Kml
 * @author Ontic Soluciones
 *
 */
public class ListaKml extends ListActivity {	

	private ArrayList<String> tablas = new ArrayList<String>();
	private List<String> vista = new ArrayList<String>();
	private SQLiteDatabase myDB;
	private DataBaseHelper db;
	private Context context;
	private String s;
	private String result="";
	private int posicion;
	private ProgressDialog dialog;
	private Handler handler;

	/**
	 * Llamado al crear la actividad.
	 * Hace un ls en la carpeta donde las guarda por defecto, así si detecta un fichero con el mismo
	 * nombre muestra un asterisco (*) para avisar al usuario de que esa tabla ya está exportada.
	 * Luego crea una instancia de la clase que exporta y muestra un mensaje final.
	 */
	public void onCreate(Bundle savedInstanceState)
	{
      super.onCreate(savedInstanceState);
      
	 
      db = new DataBaseHelper(this);
      myDB = db.getReadableDatabase();
	  context = (this);        

		try {
			Process p = Runtime.getRuntime().exec("ls "+Environment.getExternalStorageDirectory().getAbsolutePath()+"/kmls");

			BufferedReader stdInput = new BufferedReader(new InputStreamReader(
			                p.getInputStream()));

			while ((s = stdInput.readLine()) != null) 
			{
			       result+= " "+s;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
      
      Cursor tables = myDB.rawQuery("select * from sqlite_sequence ORDER BY NAME DESC",null);
      tables.moveToFirst();
      
      if(tables.moveToFirst())
      for(int i =0; i<tables.getCount(); i++)
      {
    	  String aux;
    	  aux = tables.getString(0);
    	  if(aux.charAt(0)== 't')
    	  {
    		  aux = aux.substring(1);
    		  if(result.contains("t"+aux+".kml"))
    			  vista.add(""+aux.substring(6)+"/"+aux.substring(4, 6)+"/"+aux.substring(0, 4)+" (*)"); 
    		  else
    			  vista.add(""+aux.substring(6)+"/"+aux.substring(4, 6)+"/"+aux.substring(0, 4)); 
    		  tablas.add(aux);
    	  }
    	  tables.moveToNext();
      }
      myDB.close();
      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      setListAdapter(new ArrayAdapter<String>(this, R.layout.lista_wifis, vista));
      
      handler = new Handler(){
  	    public void handleMessage(Message msg) {
  	         if(msg.what == 0)
  	         {
  	                dialog.dismiss();
  	                Toast.makeText(getApplicationContext(),context.getString(R.string.exported),Toast.LENGTH_SHORT).show();
            	       Toast.makeText(getApplicationContext(),"Terminado",Toast.LENGTH_SHORT).show();
  	                ((Activity) context).finish();
  	         }
  	   }
    };
    
      lv.setOnItemClickListener(new OnItemClickListener() 
      {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id)
        {
        	
        	dialog = ProgressDialog.show(context, "", 
                    context.getString(R.string.export), true);
              posicion = position;
              
              new Thread(){
            	  public void run()
            	  {
            		  Kml kml = new Kml(context,"t"+tablas.get(posicion));
           	          kml.copiar();
           	          handler.sendEmptyMessage(0);
            	  }
              }.start();
           }
      });
	
	}
	
	public boolean onCreateOptionsMenu(Menu menu) 
	{
        menu.add(0, 2, 0, R.string.draw_map).setIcon(android.R.drawable.ic_menu_mapmode);
		
        return(super.onCreateOptionsMenu(menu));
    }
    

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    // Handle item selection
	    switch (item.getItemId()) {

	    case 2:
	    	Intent intent = new Intent(this,PintaMapa.class);
			startActivity(intent);

	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public void onPause()
	{
		super.onPause();
	}
}